<template>
  <div :id="mapId" class="map-container">
    <div v-if="popInfo" id="popInfo">
      <slot name="infoContent" />
    </div>
    <!-- Google地图/天地图使用  -->
    <div v-if="baseLayerMode" id="map-switcher">
      <el-radio-group v-model="mapType" size="mini">
        <el-radio-button label="vector">矢量</el-radio-button>
        <el-radio-button label="image">卫星</el-radio-button>
        <el-radio-button label="terrain">地形</el-radio-button>
      </el-radio-group>
    </div>
    <div v-if="tools" id="map-tools">
      <el-button type="primary" size="mini" @click="toolsShow = !toolsShow">工具</el-button>
      <ul v-show="toolsShow" class="tools-list">
        <li class="tools-list-item" @click="distance">测距</li>
        <li class="tools-list-item" @click="area">测面积</li>
        <li class="tools-list-item" @click="clear">清除</li>
        <li class="tools-list-item" @click="fullScreen">
          全屏
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
import AMapLoader from '@amap/amap-jsapi-loader'
import { Common } from 'cby.assist'
export default {
  props: {
      options: Object
    },
    data() {
      return {
        mapId: Common.uuid(),
        tools: false,
        popInfo: false,
        mapType: 'vector',
        baseLayerMode: null,
        toolsShow: false
      }
    },
    watch: {
      mapType(type) {
        if (this.vectorLayer) {
          this.vectorLayer.hide()
        }
        if (this.vectorMarkLayer) {
          this.vectorMarkLayer.hide()
        }
        if (this.imageLayer) {
          this.imageLayer.hide()
        }
        if (this.imageMarkLayer) {
          this.imageMarkLayer.hide()
        }
        if (this.terrainLayer) {
          this.terrainLayer.hide()
        }
        if (this.terrainMarkLayer) {
          this.terrainMarkLayer.hide()
        }
        if (type == 'vector') {
          if (this.vectorLayer) {
            this.vectorLayer.show()
          }
          if (this.vectorMarkLayer) {
            this.vectorMarkLayer.show()
          }
        } else if (type == 'image') {
          if (this.imageLayer) {
            this.imageLayer.show()
          }
          if (this.imageMarkLayer) {
            this.imageMarkLayer.show()
          }
        } else if (type == 'terrain') {
          if (this.terrainLayer) {
            this.terrainLayer.show()
          }
          if (this.terrainMarkLayer) {
            this.terrainMarkLayer.show()
          }
        }
      }
    },
    mounted() {
      AMapLoader.load({
        key: '553b778d0b57899fcdadfdbc1dab4ddd', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          'AMap.ElasticMarker',
          'AMap.ToolBar',
          'AMap.Scale',
          'AMap.HawkEye',
          'AMap.MapType',
          'AMap.Geolocation',
          'AMap.AdvancedInfoWindow',
          'AMap.AutoComplete',
          'AMap.PlaceSearch',
          'AMap.DistrictSearch',
          'AMap.LineSearch',
          'AMap.StationSearch',
          'AMap.Geocoder',
          'AMap.CitySearch',
          'AMap.MouseTool',
          'AMap.CircleEditor',
          'AMap.PolyEditor',
          'AMap.MarkerCluster',
          'AMap.RangingTool',
          'AMap.CloudDataLayer',
          'AMap.CloudDataSearch',
          'AMap.Hotspot',
          'AMap.PolygonEditor',
          'AMap.PolylineEditor',
          'AMap.MoveAnimation'
        ] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          this.initMap(AMap)
        })
        .catch((e) => {
          console.log(e)
        })
    },
    destroyed() {
      if (this.map) {
        this.map.destroy()
      }
    },
    methods: {
      initMap() {
        console.log(this.options)
        if (this.options) {
          if (this.options.options) {
            this.map = new AMap.Map(this.mapId, this.options.options)
          } else {
            this.map = new AMap.Map(this.mapId)
          }
          if (this.options.baseLayerMode) {
            this.baseLayerMode = this.options.baseLayerMode
            if (this.options.baseLayerMode == 'google') {
              this.setGoogleLayer()
            } else if (this.options.baseLayerMode == 'tdt') {
              this.setTdtLayer()
            } else if (this.options.baseLayerMode == 'arcgis') {
              this.setArcgisLayers()
            }
            if (this.options.mapType) {
              this.mapType = this.options.mapType
            }
          }
          if (this.options.controls && this.options.controls.length) {
            for (const control of this.options.controls) {
              this.map.addControl(control)
            }
          }
          if (this.options.tools === true) {
            this.tools = this.options.tools
            this.ruler = new AMap.RangingTool(this.map)
            this.ruler.on('end', (event) => this.ruler.turnOff())
            this.mouseTool = new AMap.MouseTool(this.map)
            this.mouseTool.on('draw', (event) => this.mouseTool.close())
          }
          this.popInfo = this.options.popInfo
        } else {
          this.map = new AMap.Map(this.mapId)
        }
        this.$emit('mapcreated', { AMap, map: this.map })
        this.__removeLogo__()
      },
      distance() {
        this.ruler.turnOn()
      },
      area() {
        this.mouseTool.measureArea()
      },
      clear() {
        this.ruler.turnOff(true)
        this.mouseTool.close(true)
      },
      fullScreen() {
        if (this.options && this.options.fullScreen === 'map') {
          Common.fullScreen(document.getElementById(this.mapId))
        } else {
          Common.fullScreen()
        }
      },
      __removeLogo__() {
        setTimeout(() => {
          const amap_logo = document.getElementsByClassName('amap-logo')
          if (amap_logo && amap_logo.length) {
            for (let i = 0; i < amap_logo.length; i++) {
              amap_logo[i].parentNode.removeChild(amap_logo[i])
            }
          }
          const amap_copyright =
            document.getElementsByClassName('amap-copyright')
          if (amap_copyright && amap_copyright.length) {
            for (let i = 0; i < amap_copyright.length; i++) {
              amap_copyright[i].parentNode.removeChild(amap_copyright[i])
            }
          }
        }, 500)
      },
      setGoogleLayer() {
        this.vectorLayer = this.googleLayer('m')
        this.imageLayer = this.googleLayer('y', { visible: false })
        this.terrainLayer = this.googleLayer('p', { visible: false })
        this.map.setLayers([this.vectorLayer, this.imageLayer, this.terrainLayer])
      },
      setTdtLayer() {
        this.vectorLayer = this.tdtLayer('vec_w')
        this.vectorMarkLayer = this.tdtLayer('cva_w')
        this.imageLayer = this.tdtLayer('img_w', { visible: false })
        this.imageMarkLayer = this.tdtLayer('cia_w', { visible: false })
        this.terrainLayer = this.tdtLayer('ter_w', {
          visible: false,
          dataZooms: [2, 14]
        })
        this.terrainMarkLayer = this.tdtLayer('cta_w', {
          visible: false,
          dataZooms: [2, 14]
        })
        this.districtLayer = this.tdtLayer('ibo_w')
        this.map.setLayers([
          this.vectorLayer,
          this.vectorMarkLayer,
          this.imageLayer,
          this.imageMarkLayer,
          this.terrainLayer,
          this.terrainMarkLayer,
          this.districtLayer
        ])
      },
      // 在高德里加载arcgis底图
      setArcgisLayers() {
        this.vectorLayer = new AMap.TileLayer({
          tileUrl:
            'http://cache1.arcgisonline.cn/arcgis/rest/services/ChinaOnlineCommunity/MapServer/tile/[z]/[y]/[x]'
        })
        this.imageLayer = new AMap.TileLayer({
          tileUrl:
            'https://services.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/[z]/[y]/[x]',
          visible: false
        })
        this.terrainLayer = new AMap.TileLayer({
          tileUrl:
            'https://services.arcgisonline.com/arcgis/rest/services/World_Topo_Map/MapServer/tile/[z]/[y]/[x]',
          visible: false
        })
        this.map.setLayers([this.vectorLayer, this.imageLayer, this.terrainLayer])
      },
      // 在高德里加载google底图
      googleLayer(type, opt = {}) {
        return new AMap.TileLayer(
          Object.assign(
            {
              // tileUrl: `http://mt{0-3}.google.cn/vt/lyrs=${type}@142&hl=zh-CN&gl=cn&s=Galil&x={x}&y={y}&z={z}`,
              // tileUrl: `https://gac-geo.googlecnapps.cn/maps/vt?lyrs=${type}&gl=CN&x={x}&y={y}&z={z}`,
              tileUrl: `http://mt{0,1,2,3}.google.cn/vt/lyrs=${type}@142&hl=zh-CN&gl=cn&x=[x]&y=[y]&z=[z]&s=Galil`
            },
            opt
          )
        )
      },
      // 在高德里加载天地图底图
      tdtLayer(type, opt = {}) {
        if (!opt.key) {
          opt.key = 'd7fcef2a4ffdf0c94810504c5403c2c9'
        }
        return new AMap.TileLayer(
          Object.assign(
            {
              tileUrl: `http://t{0,1,2,3,4,5,6,7}.tianditu.gov.cn/DataServer?T=${type}&x=[x]&y=[y]&l=[z]&tk=${opt.key}`
            },
            opt
          )
        )
      },
      bingLayer() {
        return new AMap.TileLayer({
          zooms: [3, 20],
          getTileUrl(x, y, z) {
            const array = []
            for (let i = z; i > 0; i--) {
              let num = 0
              const mask = 1 << (i - 1)
              if ((x & mask) != 0) {
                num++
              }
              if ((y & mask) != 0) {
                num += 2
              }
              array.push(num)
            }
            const key = array.join('')
            const url = `https://t0.dynamic.tiles.ditu.live.com/comp/ch/${key}?mkt=zh-CN&ur=CN&it=G,TW,RL&n=z&og=473&cstl=rd`
            return url
          }
        })
      },
    }
}
</script>
<style scoped>
.map-container {
  width: 100%;
  height: 100%;
}
#popInfo {
  position: absolute;
  left: 20px;
  top: 60px;
  width: calc(27% - 5px);
  height: calc(100% - 400px);
  background: #ffffff;
  z-index: 1;
}
#map-switcher {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 1;
}
#map-tools {
  position: absolute;
  top: 60px;
  right: 20px;
  z-index: 1;
}

.tools-list {
  padding: 0;
  margin: 0;
  list-style: none;
  border-radius: 4px;
  overflow: auto;
  cursor: pointer;
}

.tools-list-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 28px;
  background: white;
  color: #606266;
  font-size: 12px;
}

.tools-list-item:hover {
  background: #e8f3fe;
}
</style>
